// shop page
// ============

define(['zepto', 'sui', 'utils', 'JST', 'wxshare'], 
function($, sui, utils, JST, wxshare) {
  return {
    init: function(data) {
      this.data = data;
      this.model = {
        'roundId': data.roundId,
      }
      
      this.initPage(data);
      
      if(data.sites != null) this.bindSiteSelect(data.sites, data.currentSite, data.currentSiteName);
      
      this.bindAppointmentSubmitAction()
      
    },
    
    initPage: function(data) {
      // forbidden wx share
      wxshare.initShare(data.jsConfig, false)
    },
    
    refreshPage: function() {
      var that = this,
      day = $('input[name="day"]').val().trim(),
      site = $('input[name="site"]').val().trim()
      
      setTimeout(function(){
        window.location.href= window.__CTX__.root + "/profile/courses/" + that.model.roundId + "/appointment?site="+ site +"&day=" + day + "&scheduleId=" + that.data.scheduleId;
      }, 100)
      
    },
    
    bindSiteSelect: function(sites, current, currentName) {
        
        that = this
        
        var $siteSelector = $("input[name='siteSelector']");
            
        var displayValues = []
        var values = []
        
        for(var i in sites) {
          values.push(sites[i].id)
          displayValues.push(sites[i].name)
        }
        
        $siteSelector.picker({
          toolbarTemplate: '<header class="bar bar-nav">\
                              <button class="button button-link pull-right close-picker">确定</button>\
                              <h1 class="title">请选择门店</h1>\
                           </header>',
          cols: [
            {
              textAlign: 'center',
              values: values,
              displayValues: displayValues
            }
          ],
          formatValue: function (picker, value, displayValue){
            $(this.input).next().val(value)
            return displayValue
          },
          onClose: function() {
            that.refreshPage();
          }
        });
        
        $siteSelector.picker("mySetValue", [current]);
    },

    // order submit evvent handler
    bindAppointmentSubmitAction: function() {
      
      var thatSubmit = this
      
      var submitButton = $("a.booking-btn")
      
      
      submitButton.on('click', function(e){
        e.preventDefault();
        
        var hour = $(this).data("hour");
        $('input[name="hour"]').val(hour);
        
        // init all data
        var data = thatSubmit.onInitData()
        // validate all input
        if(thatSubmit.onValidateData(data)) {
          // do submit order with data
          data = thatSubmit.onAppendData(data)
          thatSubmit.onSubmitOrder(data)
        }
      })
      
    },
    /*bindAppointmentSubmitAction: function() {
      var thatSubmit = this
    
      var submitButton = $(".item.available a")
        
      submitButton.on('click', function(e){
        e.preventDefault();
      
        var hour = $(this).data("hour");
        $('input[name="hour"]').val(hour);
      
        // init all data
        var data = thatSubmit.onInitData()
        // validate all input
        if(thatSubmit.onValidateData(data)) {
          // do submit order with data
          data = thatSubmit.onAppendData(data)
          thatSubmit.onSubmitOrder(data)
        }
      })
    },*/
    
    // init data
    onInitData: function() {
      return {
        '_method': {
          'value': 'PATCH'
        },
        'roundId': {
          'value': this.model.roundId,
          'message': '课程不能为空'
        },
        'siteId': {
          'value': $('input[name="site"]').val().trim(),
          'message': '门店不能为空'
        },
        'day': {
          'value': $('input[name="day"]').val().trim(),
          'message': '日期不能为空'
        },
        'hour': {
          'value': $('input[name="hour"]').val(),
          'message': '请勾选上课时间段'
        }
      }
    },

    onAppendData: function(data) {
	  data.scheduleId = {
	        'value': this.data.scheduleId
	      }
      return data;
    },

    onValidateData: function(data) {
      var valid = _.find(data, function(item) {
        return !item.value
      })

      if (!!valid) return $.toast(valid.message)

      return true
    },

    onSubmitOrder: function(data) {
      
      var that = this
      /*$.showPreloader('正在查询可预约教练')*/

      var processedData = _.mapObject(data, function(obj) {
        return obj.value
      })
      
      var url = $("form.check-form").attr("action");
      
      $.ajax({
        type: 'POST',
        url: url,
        data: processedData
      }).done(function(response) {
        $.hidePreloader()
        utils.processResult(response, function(result) {
          that.showCoachSelect(result.data)
        }, function(result) {
          $.toast(result.message || '查询可预约教练失败')
        })
      })
    },
    
    showCoachSelect: function(data) {
      var appointment = JSON.parse(data.appointment);
      var coaches = JSON.parse(data.coaches);
      var roomPrepare = JSON.parse(data.roomPrepare);
      var roomLimit = roomPrepare.roomLimit;
      var commonLimit = roomPrepare.commonLimit;
      var roomRemain = roomPrepare.roomRemain;
      var commonRemain = roomPrepare.commonRemain;
      var that = this;
      var $page = $(JST.areaSelectTpl({
        'CTX': __CTX__,
        'roundId': that.model.roundId,
        'scheduleId': that.data.scheduleId,
        'siteId':  appointment.siteId,
        'day':     appointment.dayString,
        'hour':    appointment.hour,
        'coaches': coaches,
        'roomName': '私人区域',
        'commonName': that.data.fuxing == 'true' ? '米域' : '公共区域',
        'roomLimit': roomLimit,
        'commonLimit': commonLimit,
        'roomRemain': roomRemain,
        'commonRemain': commonRemain
      }))
      
      var coachDisplay = new Array(),
          coachValue = new Array();
      $.each(coaches, function(k, coach) {
        coachDisplay[k] = coach.principal.name + "-" + coach.status;
        coachValue[k] = coach.principal.id;
      })
      
      // Bind submit
      that.bindCoachSelectEvent($page, coachDisplay, coachValue)
      
      $.push.transitionIn($page)
    },
    
    bindCoachSelectEvent: function($page, coachDisplay, coachValue) {
      var that = this;
      
      var $areaInput = $page.find("input[name='areaType']").each(function(){
        if(!$(this).hasClass("unchecked")) {
          $(this).prop("checked", true);
        } else {
          $(this).prop("checked", false);
        }
      })
      
      
      $page.on('click', ".area-select", function(e){
        $(".area-select").removeClass("active");
        $(".area-select").find("input[name='areaType']").prop("checked", false);
        $(this).addClass("active");
        $(this).find("input[name='areaType']").prop("checked", true);
          
        var coachId = $("input[name='coachId']:checked").val();
        if(coachId) {
          $(".submit-fixed").show();
        } 
        
      });
      
      $page.on('click', ".course-booking li .active-button", function(e){
        $(".course-booking li").removeClass("active");
        $(".course-booking li").find('.active-button').html("可预约");
        $(".course-booking li").find("input[name='coachId']").prop("checked", false);
        $(this).html("已选择").parents("li").addClass("active");
        $(this).parents("li").find("input[name='coachId']").prop("checked", true);
        
        var areaType  = $("input[name='areaType']:checked").val();
        if(!areaType) {
            return  $.toast('请选择区域');
        } else {
            $(".submit-fixed").show();
        }
        
        
      });
      
      $page.on('click', "a[href='#coach-appointment']", function(e){
          var site      = $("input[name='siteId']").val();
          var day       = $("input[name='day']").val();
          var roundId   = $("input[name='roundId']").val()
          /*var areaType  = $("input[name='areaType']:checked").val();
          if(!areaType) {
              return  $.toast('请选择区域');
          }*/
          
          var coachId = $(this).data("coach")
          window.location.href = window.__CTX__.root + "/profile/courses/" + roundId + "/coaches/" + 
          coachId + "/appointment?site=" + site + "&day=" + day + "&scheduleId=" + that.data.scheduleId;
         
      });
      
      $page.on('click', '#submit', function(e) {
        e.preventDefault();
        
        var areaType = $("input[name='areaType']:checked").val();
        if(!areaType) {
            return  $.toast('请选择区域');
        }
        
        var coachId = $("input[name='coachId']:checked").val();
        if(!coachId) {
          return  $.toast('请选择教练');
        }
        
        $.showPreloader('正在提交预约')
        var $form = $($page).find("form");
        console.log($form.serializeArray())
        $.post($($form).attr("action"), $form.serializeArray()).done(
          function(response) {
            $.hidePreloader()
            utils.processResult(response, function(result) {
              $.toast(result.message || "预约成功")
              setTimeout(function() {
                window.location.href = __CTX__.root + "/profile/courses/" + that.model.roundId;
              }, 1000)
            }, function(result) {
              $.toast(result.message || '预约失败')
           })
        })
      })
    }
  }
})